'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
let res_num;
exports.main = async (event) => {
	if (event.type == 'checkNum') {
		//查宿舍号是否存在
		res_num = await db.collection("room").where({
			school: event.school,
			floor: event.floor,
			roomNum: event.roomNum,
			uid: event.uid
		}).get();
		return res_num;
	} else if (event.type == 'setRoom') {
		return await db.collection("room").where({
			_id: event.roomId
		}).update({
			school: event.school,
			roomNum: event.roomNum,
			roomtype: event.roomtype,
			members: event.members,
			floor: event.floor,
			createtime: event.createtime
		})
	} else if (event.type == "delRoom") {
		//删除宿舍
		//开启事务，删除宿舍后用户表中的ishave-1否则回滚
		const transaction = await db.startTransaction() //开启事务
		try {
			const resDel = await transaction.collection("room").doc(event.roomId).remove();
			const resGet = await transaction.collection("roomcenteruser").doc(event.uid).get();
			//console.log(resDel.deleted);
			//console.log(resGet.data.ishave);
			if (resDel.deleted && resGet.data.ishave > 0) {
				const resUpdate = await transaction.collection("roomcenteruser").doc(event.uid).update({
					ishave: dbCmd.inc(-1)
				});
				const resIsHave = await transaction.collection("roomcenteruser").doc(event.uid).get();
				if (resUpdate.updated) {
					await transaction.commit();
					return {
						success: true,
						ishave: resIsHave.data.ishave
					}
				}
			}
		} catch (e) {
			//TODO handle the exception
			console.log(e);
			await transaction.rollback(-100)
			return {
				success: false,
				error: `rollback`,
				rollbackCode: -100,
			}
		}
	} else {
		//开启事务，创建宿舍后修改用户表中的ishave+1否则回滚
		const transaction = await db.startTransaction() //开启事务
		try {
			const resaaa = await transaction.collection("room").add({
				school: event.school,
				roomNum: event.roomNum,
				roomtype: event.roomtype,
				members: event.members,
				floor: event.floor,
				uid: event.uid,
				createtime: event.createtime
			});
			const resbbb = await transaction.collection("roomcenteruser").doc(event.uid).update({
				ishave: dbCmd.inc(1)
			});
			if (resaaa.id && resbbb.updated) {
				await transaction.commit();
				return {
					success: true
				}
			}
		} catch (e) {
			console.log(e);
			await transaction.rollback(-100)
			return {
				success: false,
				error: `rollback`,
				rollbackCode: -100,
			}
		}
	}
};